import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2025-01-14
 * Time: 21:50
 */
public class ReflectClassDemo {
    // 创建对象

    public static void reflectNewInstance() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class<?> c = Class.forName("Student");

        Student student = (Student) c.newInstance();

        System.out.println(student);

    }

    // 反射私有的构造方法
    public static void reflectPrivateConstructor(){


        try {
            Class<?> c1 = Class.forName("Student");
            Constructor<?> constructor = c1.getDeclaredConstructor(String.class, int.class);

            constructor.setAccessible(true);

            Student student = (Student) constructor.newInstance("xiaotao", 15);

            System.out.println(student);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }


    // 反射私有属性
    public static void reflectPrivateField() {
        try {
            Class<?> c1 = Class.forName("Student");

            Student student = (Student) c1.newInstance();
            Field field = c1.getDeclaredField("name");
            field.setAccessible(true);

            field.set(student, "aoe");
            System.out.println(student);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static void reflectPrivateMethod() {
        try {
            Class<?> c1 = Class.forName("Student");
            Method method = c1.getDeclaredMethod("function", String.class);
            method.setAccessible(true);
            Student student = (Student) c1.newInstance();
            method.invoke(student, "我是一个参数!");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        reflectPrivateMethod();
    }
}
